<template>
  <el-dialog :title="title" :visible.sync="visible" width="1000px"
             :show-close="false" :close-on-click-modal="false"	>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="关联商品" prop="assNumber">
        <el-input v-model="form.assNumber" placeholder="关联商品编号" disabled/>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <treeselect
              v-model="form.brandId"
              :options="options.brandOptions"
              :disabled="isDisabled()"
              placeholder="请选择商品品牌" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="typeId">
            <treeselect
              v-model="form.typeId"
              :options="options.gTypeOptions"
              :disabled="isDisabled()"
              @input="handleTypeInput"
              placeholder="请选择商品类型" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品编码" prop="gNumber">
            <el-input v-model="form.gNumber" placeholder="商品编码" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="顺序" prop="orderNum">
            <el-input v-model="form.orderNum" type="number" placeholder="请输入显示顺序" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="价格" prop="price">
            <el-input v-model="form.price" type="number" placeholder="请输入价格" @input="handleInput" >
              <template slot="append">分</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存" prop="stockQuantity">
            <el-input v-model="form.stockQuantity" type="number" placeholder="请输入库存" @input="handleInput" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="form.goodsName" placeholder="请输入商品名称" :disabled="!!goodsId"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="属性分类" >
          <el-transfer
            v-model="form.attrs"
            :data="options.attrOptions"
            target-order="push"
            :titles="['属性列表', '分类列表']"
          >
            <el-button v-if="form.assNumber" class="transfer-footer" slot="right-footer"
                       size="small" type="primary" @click="handleAssort" >获取父分类</el-button>
          </el-transfer>
        </el-form-item>
      </el-row>
      <el-form-item label="封面图片" prop="image">
        <div style="width: 200px; display: inline-grid;">
          <image-upload ref="uploadImage" v-model="form.image" :auto-upload="false" :limit="1"
                        @success="handleImageSuccess" style="width: 500px;" />
        </div>
        <el-button @click="openSelectImage" type="success" plain>选择已上传图片</el-button>
      </el-form-item>
      <el-form-item label="" prop="image">
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="上架状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择上架状态">
              <el-option
                v-for="dict in dict.type.sys_goods_sj_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="delFlag">
            <el-radio-group v-model="form.delFlag">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <image-select ref="select" :params="{ imageType: '1' }" @ok="handleSelectOk" />

  </el-dialog>

</template>
<script>
import { getMainByGNumber, addMain, updateMain, findMaxOrderNum, getMain } from '@/api/goods/main'
import { treeSelect as optionBrandSelect } from "@/api/goods/brand";
import { treeSelect as optionGTypeSelect } from "@/api/goods/type";
import { typeAttrTreeOptions as optionAttrSelect } from "@/api/goods/attr";

import Treeselect from '@riophae/vue-treeselect'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageSelect from '@/views/goods/images/components/selectImage.vue'

export default {
  components: { Treeselect, ImageSelect },
  dicts: ['sys_normal_disable', 'sys_goods_sj_status'],
  props: {
    params: {
      type: Object,
      default: {}
    }
  },
  data() {
    // 定义自定义验证函数
    const validatePositiveInteger = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入数字'));
      }
      setTimeout(() => {
        if (!Number.isInteger(Number(value)) || Number(value) <= 0) {
          callback(new Error('请输入正整数'));
        } else {
          callback();
        }
      }, 100);
    };
    return {
      visible: false,
      title: '新增商品',
      gNumber: null,
      goodsId: null,
      isInitialized: true,
      // 本地图片资源地址
      imgServe: process.env.VUE_APP_BASE_API,
      // 下拉列表
      options: {
        brandOptions: [],
        gTypeOptions: [],
        parentOptions: [],
        attrOptions: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "商品品牌不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "商品类型不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" },
          { validator: validatePositiveInteger, trigger: "blur" }
        ],
      },
    }
  },
  methods: {
    /** 查询商品品牌下拉树结构 */
    getBrandTreeSelect() {
      optionBrandSelect().then(response => {
        this.options.brandOptions = response.data;
      });
    },
    /** 查询商品类型下拉树结构 */
    getGTypeTreeSelect() {
      optionGTypeSelect().then(response => {
        this.options.gTypeOptions = response.data;
      });
    },
    /** 类型属性 */
    getAttrTreeOptions(typeId) {
      if (typeId) {
        optionAttrSelect(typeId).then(res => {
          let list = []
          res.data.filter(o => {
            list.push(...this.generateAttrOptions(o))
          })
          this.options.attrOptions = list;
        })
      } else {
        this.options.attrOptions = [];
      }
    },
    generateAttrOptions(options) {
      let list = []
      if (options) {
        if (options.children) {
          list.push({key: options.id+'', label: options.label, disabled: true})
          options.children.filter(c => {
            list.push(...this.generateAttrOptions(c));
          })
        } else {
          list.push({key: options.id+'', label: options.label, disabled: options.disabled})
        }
      }
      return list
    },
    resetForm() {
      this.gNumber = null;
      this.goodsId = null;
      this.isInitialized = true;
      this.form = {
        goodsId: null,
        assNumber: null,
        gNumber: null,
        goodsName: null,
        brandId: null,
        typeId: null,
        price: 0,
        stockQuantity: 0,
        image: null,
        orderNum: null,
        status: '0',
        delFlag: '0',
        remark: null,
        assort: null,// 分类
        attrs: [],
      }
    },
    // 显示弹框
    show() {
      this.resetForm();
      this.getBrandTreeSelect();
      this.getGTypeTreeSelect();
      const params = this.params;
      console.log('params : ', params);
      if (params.gNumber) {
        this.gNumber = params.gNumber;
      }
      if (params.goodsId && params.goodsId > 0) {
        this.goodsId = params.goodsId;
        this.title = '修改商品主体信息';
      } else {
        this.title = '新增商品';
      }
      this.generateForm();
    },
    async generateForm() {
      if (this.goodsId && this.goodsId > 0) {
        await this.generateFormByGoodsId();
      } else if (this.gNumber) {
        await this.generateFormByGNumber();
      } else {
      }
      this.form.gNumber = null;
      const assNumber = this.form.assNumber;
      findMaxOrderNum(assNumber).then(res => {
        const num = res.data;
        this.form.orderNum = num;
        if (assNumber) {
          this.getAttrTreeOptions(this.form.typeId);
        } else {
          this.getAttrTreeOptions();
        }
        this.visible = true;
      })
    },
    async generateFormByGNumber() {
      await getMainByGNumber(this.gNumber).then(res => {
        let main = res.data;
        main.goodsId = null;
        if (!main.assNumber) {
          main.assNumber = main.gNumber;
        }
        if (main.assort) {
          main.attrs = main.assort.split(',');
        }
        this.form = main;
      })

    },
    async generateFormByGoodsId() {
      await getMain(this.goodsId).then(res => {
        let main = res.data;
        if (main.assort) {
          main.attrs = main.assort.split(',');
        }
        this.form = main;
      });
    },
    // 弹出层是否禁用
    isDisabled() {
      if (this.gNumber) {
        return true;
      }
      if (this.goodsId && this.goodsId > 0) {
        return true;
      }
      return false;
    },
    // 输入判断
    handleInput() {
      if (!this.form.price || this.form.price <= 0) {
        this.form.price = 0;
      }
      if (!this.form.stockQuantity || this.form.stockQuantity <= 0) {
        this.form.stockQuantity = 0;
      }
    },
    handleAssort() {
      this.form.attrs = []
      if (this.form.assNumber) {
        getMainByGNumber(this.form.assNumber).then(res => {
          if (res.data && res.data.assort) {
            this.form.attrs = res.data.assort.split(',');
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.attrs) {
            this.form.assort = this.listToString(this.form.attrs);
          } else {
            this.form.assort = ''
          }
          // 上传蹄片
          if (!this.form.image) {
            this.form.imageId = null;
            let files = this.$refs.uploadImage.$refs.imageUpload.uploadFiles; // 获取选中的文件列表
            if (files && files.length > 0) {
              this.$refs.uploadImage.$refs.imageUpload.submit(); // 手动调用上传
            } else {
              this.$modal.msgError("请先选择图片");
            }
          } else {
            this.submitMainForm();
          }
        }
      });
    },
    submitMainForm() {
      if (this.form.goodsId != null) {
        updateMain(this.form).then(res => {
          this.$modal.msgSuccess("修改成功");
          this.visible = false;
          const gNumber = res.data;
          console.log('edit gNumber: ', gNumber);
          this.$emit('success', gNumber);
        });
      } else {
        addMain(this.form).then(res => {
          this.$modal.msgSuccess("新增成功");
          this.visible = false;
          const gNumber = res.data;
          console.log('ADD gNumber: ', gNumber);
          this.$emit('success', gNumber);
        });
      }
    },
    handleImageSuccess(fileList) {
      this.submitMainForm()
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i] + separator;
      }
      return strs != '' ? strs.substring(0, strs.length - 1) : '';
    },
    handleTypeInput(val) {
      if (this.isInitialized) {
        this.isInitialized = false;
      } else {
        this.form.attrs = []
        this.getAttrTreeOptions(val);
      }
    },
    /** 打开授权用户表弹窗 */
    openSelectImage() {
      this.$refs.select.show();
    },
    /** 选择图片后 */
    handleSelectOk(val) {
      if (val && val.length === 1) {
        const image = val[0];
        this.form.imageId = image.imageId;
        this.form.image = image.imagePath;
      }
    },
    // 取消按钮
    cancel() {
      this.visible = false;
      this.resetForm();
    },
  }
}
</script>

<style scoped>
::v-deep .el-form {
  display: block !important;
}
</style>
